package com.umakr.ax.security.service;

import com.umakr.ax.security.mapper.UserMapper;
import com.umakr.ax.security.model.SecurityUser;
import com.umakr.ax.security.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 *
 * @author Administrator
 * @date 2015/9/14
 */
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private UserMapper userMapper;

    private static final String ACCOUNT_CONTAINS = "@";

    @Override
    public UserDetails loadUserByUsername(String account) {
        User user = new User();
        if(account.contains(ACCOUNT_CONTAINS)){
            user.setId(Long.parseLong(account.replace("@","")));
        }else{
            user.setAccount(account);
        }
        user = userMapper.selectOne(user);
        if(user != null){
            return new SecurityUser(user);
        }else{
            throw new UsernameNotFoundException("用户名不存在。");
        }
    }
    public String encodePassword(String u,String p){
        Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
        return md5PasswordEncoder.encodePassword(p,u);
    }

    public User currentUser(){
        return  (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
